<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天室管理后台</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .room-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        .room-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: relative;
        }
        .room-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #1a73e8;
        }
        .user-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .user-item {
            padding: 8px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .user-item:last-child {
            border-bottom: none;
        }
        .kick-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
        }
        .kick-btn:hover {
            background: #c82333;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #1a73e8;
        }
        .stat-label {
            color: #666;
            margin-top: 5px;
        }
        .room-management {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .room-form {
            display: grid;
            gap: 15px;
            margin-bottom: 20px;
        }
        .room-form input, .room-form textarea {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .room-form textarea {
            height: 80px;
            resize: vertical;
        }
        .delete-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        .delete-btn:hover {
            background: #c82333;
        }
        .room-messages {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #eee;
            padding: 10px;
            margin-top: 10px;
            border-radius: 4px;
            background: #f8f9fa;
            display: none;
        }
        .message-item {
            padding: 5px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
        }
        .message-item:last-child {
            border-bottom: none;
        }
        .message-time {
            color: #666;
            font-size: 12px;
            margin-right: 5px;
        }
        .message-user {
            color: #1a73e8;
            font-weight: bold;
        }
        .toggle-messages {
            position: absolute;
            top: 20px;
            right: 20px;
            background: #1a73e8;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        .toggle-messages:hover {
            background: #1557b0;
        }
        .room-stats {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #eee;
        }
        .room-stat {
            background: #f8f9fa;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            color: #666;
        }
        .room-info {
            margin: 10px 0;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 4px;
        }
        .room-info p {
            margin: 5px 0;
            color: #666;
            font-size: 14px;
        }
        .room-info p strong {
            color: #1a73e8;
            font-weight: normal;
        }
        .user-management {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .user-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        .user-table th, .user-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        .user-table th {
            background: #f8f9fa;
            font-weight: bold;
            color: #1a73e8;
        }
        .user-table tr:hover {
            background: #f8f9fa;
        }
        .admin-badge {
            background: #1a73e8;
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>聊天室管理后台</h1>
        </div>
        
        <div class="user-management">
            <h2>用户管理</h2>
            <table class="user-table">
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>密码</th>
                        <th>身份</th>
                    </tr>
                </thead>
                <tbody id="userTableBody">
                    <!-- 用户列表将通过JavaScript动态添加 -->
                </tbody>
            </table>
        </div>
        
        <div class="room-management">
            <h2>创建新聊天室</h2>
            <div class="room-form">
                <input type="text" id="roomId" placeholder="房间ID（唯一标识）">
                <input type="text" id="roomName" placeholder="房间名称">
                <textarea id="roomDescription" placeholder="房间描述（可选）"></textarea>
                <input type="submit" value="创建房间" onclick="createRoom()">
            </div>
        </div>

        <div class="stats">
            <div class="stat-card">
                <div class="stat-number" id="totalRooms">0</div>
                <div class="stat-label">活跃房间数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="totalUsers">0</div>
                <div class="stat-label">在线用户数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="totalMessages">0</div>
                <div class="stat-label">消息总数</div>
            </div>
        </div>

        <div class="room-container" id="roomContainer">
            <!-- 房间卡片将通过JavaScript动态添加 -->
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script>
        const socket = io({
            query: {
                auth: '123456'
            }
        });
        let messageCount = 0;

        // 存储每个房间的消息
        const roomMessages = {};

        function updateRoomCard(roomData) {
            const roomContainer = document.getElementById('roomContainer');
            const existingCard = document.getElementById(`room-${roomData.room}`);
            
            const roomHtml = `
                <div class="room-title">房间: ${roomData.name}</div>
                <div class="room-info">
                    <p>创建者: ${roomData.created_by}</p>
                    <p>创建时间: ${roomData.created_at}</p>
                    <p>描述: ${roomData.description || '暂无描述'}</p>
                </div>
                <button class="toggle-messages" onclick="toggleMessages('${roomData.room}')">查看消息</button>
                <ul class="user-list">
                    ${Object.entries(roomData.users).map(([sid, userData]) => `
                        <li class="user-item">
                            <span>${userData.username} (${userData.gender === 'female' ? '女' : '男'})</span>
                            <button class="kick-btn" onclick="kickUser('${roomData.room}', '${sid}', '${userData.username}')">踢出</button>
                        </li>
                    `).join('')}
                </ul>
                <div class="room-messages" id="messages-${roomData.room}" style="display: none;">
                    <!-- 消息将动态添加到这里 -->
                </div>
                <div class="room-stats">
                    <div class="room-stat">在线用户: ${Object.keys(roomData.users).length}</div>
                    <div class="room-stat">消息数: <span id="message-count-${roomData.room}">${roomMessages[roomData.room]?.length || 0}</span></div>
                </div>
                <button class="delete-btn" onclick="deleteRoom('${roomData.room}')">删除房间</button>
            `;
            
            if (existingCard) {
                // 更新现有房间卡片
                existingCard.innerHTML = roomHtml;
            } else {
                // 创建新房间卡片
                const roomCard = document.createElement('div');
                roomCard.className = 'room-card';
                roomCard.id = `room-${roomData.room}`;
                roomCard.innerHTML = roomHtml;
                roomContainer.appendChild(roomCard);
                
                // 初始化房间消息
                if (!roomMessages[roomData.room]) {
                    roomMessages[roomData.room] = [];
                }
            }
        }

        function kickUser(room, sid, username) {
            socket.emit('admin_kick_user', {
                room: room,
                sid: sid,
                username: username
            });
        }

        function updateStats(data) {
            document.getElementById('totalRooms').textContent = Object.keys(data).length;
            let totalUsers = 0;
            Object.values(data).forEach(room => {
                totalUsers += Object.keys(room.users).length;
            });
            document.getElementById('totalUsers').textContent = totalUsers;
            document.getElementById('totalMessages').textContent = messageCount;
        }

        socket.on('admin_update', function(data) {
            // 清空现有房间容器
            document.getElementById('roomContainer').innerHTML = '';
            
            // 更新每个房间
            Object.entries(data).forEach(([roomId, roomData]) => {
                updateRoomCard({
                    room: roomId,
                    ...roomData
                });
            });
            
            // 更新统计信息
            document.getElementById('totalRooms').textContent = Object.keys(data).length;
            let totalUsers = 0;
            Object.values(data).forEach(room => {
                totalUsers += Object.keys(room.users).length;
            });
            document.getElementById('totalUsers').textContent = totalUsers;
            document.getElementById('totalMessages').textContent = messageCount;
        });

        socket.on('message_count_update', function(count) {
            messageCount = count;
            document.getElementById('totalMessages').textContent = count;
        });

        // 连接后请求初始数据
        socket.on('connect', function() {
            socket.emit('admin_request_update');
            // 请求用户列表数据
            fetchUsers();
        });

        async function createRoom() {
            const roomId = document.getElementById('roomId').value;
            const roomName = document.getElementById('roomName').value;
            const roomDescription = document.getElementById('roomDescription').value;
            
            if (!roomId || !roomName) {
                alert('请填写房间ID和名称');
                return;
            }
            
            try {
                const response = await fetch('/api/rooms', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        room_id: roomId,
                        name: roomName,
                        description: roomDescription,
                        username: 'admin'
                    })
                });
                
                const data = await response.json();
                if (data.success) {
                    alert('房间创建成功');
                    // 清空表单
                    document.getElementById('roomId').value = '';
                    document.getElementById('roomName').value = '';
                    document.getElementById('roomDescription').value = '';
                } else {
                    alert(data.message);
                }
            } catch (error) {
                alert('创建房间失败，请稍后重试');
                console.error('Create room error:', error);
            }
        }

        async function deleteRoom(roomId) {
            if (!confirm('确定要删除该房间吗？这将断开所有用户的连接。')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/rooms/${roomId}?username=admin`, {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                if (data.success) {
                    alert('房间删除成功');
                } else {
                    alert(data.message);
                }
            } catch (error) {
                alert('删除房间失败，请稍后重试');
                console.error('Delete room error:', error);
            }
        }

        function toggleMessages(roomId) {
            const messagesDiv = document.getElementById(`messages-${roomId}`);
            const button = messagesDiv.previousElementSibling.previousElementSibling;
            if (messagesDiv.style.display === 'none') {
                messagesDiv.style.display = 'block';
                button.textContent = '隐藏消息';
            } else {
                messagesDiv.style.display = 'none';
                button.textContent = '查看消息';
            }
        }

        // 监听新消息
        socket.on('message', function(data) {
            const roomId = data.room;
            if (!roomMessages[roomId]) {
                roomMessages[roomId] = [];
            }
            
            const now = new Date();
            const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
            
            roomMessages[roomId].push({
                time: timeStr,
                username: data.username,
                message: data.message
            });
            
            // 限制每个房间存储的消息数量
            if (roomMessages[roomId].length > 100) {
                roomMessages[roomId].shift();
            }
            
            // 更新消息显示
            updateRoomMessages(roomId);
            
            // 更新消息计数
            const countElement = document.getElementById(`message-count-${roomId}`);
            if (countElement) {
                countElement.textContent = roomMessages[roomId].length;
            }
        });

        function updateRoomMessages(roomId) {
            const messagesDiv = document.getElementById(`messages-${roomId}`);
            if (messagesDiv && roomMessages[roomId]) {
                messagesDiv.innerHTML = roomMessages[roomId].map(msg => {
                    if (msg.username === 'System') {
                        return `
                            <div class="message-item">
                                <span class="message-time">[${msg.time}]</span>
                                <span class="message-content">${msg.message}</span>
                            </div>
                        `;
                    } else {
                        return `
                            <div class="message-item">
                                <span class="message-time">[${msg.time}]</span>
                                <span class="message-user">${msg.username}:</span>
                                <span class="message-content">${msg.message}</span>
                            </div>
                        `;
                    }
                }).join('');
                
                // 如果消息面板是展开的，滚动到底部
                if (messagesDiv.style.display !== 'none') {
                    messagesDiv.scrollTop = messagesDiv.scrollHeight;
                }
            }
        }

        async function fetchUsers() {
            try {
                const response = await fetch('/api/users?token=123456');
                const data = await response.json();
                if (data.success) {
                    updateUserTable(data.users);
                } else {
                    console.error('Failed to fetch users:', data.message);
                }
            } catch (error) {
                console.error('Error fetching users:', error);
            }
        }

        function updateUserTable(users) {
            const tbody = document.getElementById('userTableBody');
            tbody.innerHTML = '';
            
            Object.entries(users).forEach(([username, userData]) => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${username}</td>
                    <td>${userData.password}</td>
                    <td>${userData.is_admin ? '<span class="admin-badge">管理员</span>' : '普通用户'}</td>
                `;
                tbody.appendChild(tr);
            });
        }

        function updateRoomData(data) {
            const roomList = document.getElementById('roomList');
            roomList.innerHTML = '';
            
            Object.entries(data).forEach(([roomId, room]) => {
                const roomDiv = document.createElement('div');
                roomDiv.className = 'room-item';
                
                const roomHeader = document.createElement('div');
                roomHeader.className = 'room-header';
                roomHeader.innerHTML = `
                    <h3>房间: ${room.name}</h3>
                    <p>创建者: ${room.created_by}</p>
                    <p>创建时间: ${room.created_at}</p>
                    <p>描述: ${room.description}</p>
                `;
                
                const userList = document.createElement('div');
                userList.className = 'user-list';
                userList.innerHTML = '<h4>在线用户:</h4>';
                
                if (room.users && Object.keys(room.users).length > 0) {
                    const userTable = document.createElement('table');
                    userTable.className = 'user-table';
                    userTable.innerHTML = `
                        <tr>
                            <th>用户名</th>
                            <th>性别</th>
                            <th>操作</th>
                        </tr>
                    `;
                    
                    Object.entries(room.users).forEach(([sid, userData]) => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                            <td>${userData.username}</td>
                            <td>${userData.gender === 'female' ? '女' : '男'}</td>
                            <td>
                                <button class="kick-btn" onclick="kickUser('${roomId}', '${sid}', '${userData.username}')">踢出</button>
                            </td>
                        `;
                        userTable.appendChild(tr);
                    });
                    
                    userList.appendChild(userTable);
                } else {
                    userList.innerHTML += '<p>暂无在线用户</p>';
                }
                
                roomDiv.appendChild(roomHeader);
                roomDiv.appendChild(userList);
                roomList.appendChild(roomDiv);
            });
        }
    </script>
</body>
</html> 